// API服务配置
import config from '../config'

// 检查是否为绝对URL
const isAbsoluteURL = (url: string): boolean => {
  return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url)
}

// 合并URL
const combineURLs = (baseURL: string, relativeURL?: string): string => {
  return relativeURL 
    ? `${baseURL.replace(/\/+$/, '')}/${relativeURL.replace(/^\/+/, '')}` 
    : baseURL
}

// 构建完整URL
const buildURL = (url: string): string => {
  if (isAbsoluteURL(url)) {
    return url
  }
  return combineURLs(config.api.baseURL, url)
}

// 请求配置接口
interface RequestConfig {
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'
  headers?: Record<string, string>
  body?: any
  params?: Record<string, any>
}

// 基础请求函数
const request = async (url: string, options: RequestConfig = {}) => {
  const { method = 'GET', headers = {}, body, params } = options
  
  // 构建完整URL
  let fullURL = buildURL(url)
  
  // 处理查询参数
  if (params) {
    const searchParams = new URLSearchParams(params)
    fullURL += (fullURL.includes('?') ? '&' : '?') + searchParams.toString()
  }
  
  // 合并headers
  const mergedHeaders = {
    'Content-Type': 'application/json',
    ...config.api?.headers,
    ...headers,
  }
  
  // 构建请求选项
  const fetchOptions: RequestInit = {
    method,
    headers: mergedHeaders,
    body: body ? JSON.stringify(body) : undefined,
  }
  
  try {
    const response = await fetch(fullURL, fetchOptions)
    
    // 检查响应状态
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    // 尝试解析JSON
    const contentType = response.headers.get('content-type')
    if (contentType && contentType.includes('application/json')) {
      return await response.json()
    }
    
    // 如果不是JSON，返回文本
    return await response.text()
  } catch (error) {
    console.error('API request failed:', error)
    throw error
  }
}

// API客户端
export const apiClient = {
  // GET请求
  get: <T>(url: string, params?: Record<string, any>) => 
    request(url, { method: 'GET', params }) as Promise<T>,
  
  // POST请求
  post: <T>(url: string, body?: any) => 
    request(url, { method: 'POST', body }) as Promise<T>,
  
  // PUT请求
  put: <T>(url: string, body?: any) => 
    request(url, { method: 'PUT', body }) as Promise<T>,
  
  // DELETE请求
  delete: <T>(url: string) => 
    request(url, { method: 'DELETE' }) as Promise<T>,
  
  // PATCH请求
  patch: <T>(url: string, body?: any) => 
    request(url, { method: 'PATCH', body }) as Promise<T>,
}

// 导出配置
export { config }

// 默认导出
export default apiClient